package zero.tech.games.gate.hot;

import java.util.Date;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.alibaba.cloud.commons.lang.StringUtils;
import com.alibaba.nacos.api.common.ResponseCode;

import zero.tech.core.data.PageBean;
import zero.tech.core.data.Resp;
import zero.tech.core.data.SimpleUser;
import zero.tech.core.util.DatetimeUtil;
import zero.tech.games.api.RemoteUser;
import zero.tech.games.common.Code;
import zero.tech.games.common.DiamondChangeType;
import zero.tech.games.common.MailType;
import zero.tech.games.common.RedisConsts;
import zero.tech.games.entity.games.Mail;
import zero.tech.games.entity.games.MailDel;
import zero.tech.games.entity.games.MailRead;
import zero.tech.games.entity.games.MailReward;
import zero.tech.games.gate.mapper.MailDelMapper;
import zero.tech.games.gate.mapper.MailMapper;
import zero.tech.games.gate.mapper.MailReadMapper;
import zero.tech.games.gate.mapper.MailRewardMapper;
import zero.tech.games.gate.service.api.ITradeService;
import zero.tech.redis.cache.RedisUtil;
import zero.tech.redis.lock.RedisLockUtil;
import zero.tech.redis.lock.RedisLockUtil.LockMethod;
@Component
public class MailUtil {
	@Autowired
	private RedisUtil redisUtil;
	@Autowired
	private MailMapper mailMapper;
	@Autowired
	private MailReadMapper mailReadMapper;
	@Autowired
	private MailRewardMapper mailRewardMapper;
	@Autowired
	private MailDelMapper mailDelMapper;
	@Autowired
	private RedisLockUtil lockUtil;
	@Autowired
	private ITradeService tradeService;
	@Autowired
	private RemoteUser remoteUser;

	@SuppressWarnings("unchecked")
	public PageBean<Mail> loadHotMailListByPage(int uid, Integer page, Integer pageLength) {
		int start=page*pageLength;
		PageBean<Mail> pageBean= (PageBean<Mail>) redisUtil.hget(RedisConsts.HOT_MAILLIST_BY_PAGE+"_"+uid,page+"_"+pageLength);
		if(pageBean==null) {
			int count = mailMapper.loadMailListCountByPage(uid);
			List<Mail> mails = mailMapper.loadMailListByPage(uid, start, pageLength);
			pageBean = new PageBean<>(count, pageLength, page, mails);
			if(pageBean!=null) {
				redisUtil.hset(RedisConsts.HOT_MAILLIST_BY_PAGE+"_"+uid,page+"_"+pageLength,pageBean,5*60);
			}
		}
		return pageBean;
	}

	public Resp mailRead(SimpleUser simpleUser, Integer mail_id) {
		int uid = simpleUser.getUid();
		return lockUtil.lockMethod(new LockMethod<Resp>() {

			@Override
			public Resp lockRun() {
				Mail mail = mailMapper.getMail(mail_id);
				Date now=new Date();
				String day_str=DatetimeUtil.parseDateToString("yyyy-MM-dd", now);
				if (mail == null) {
					return Resp.build(Code.MAIL_NOT_EXIT, "邮件不存在");
				}
				if (mail.getMail_type() == MailType.MAIL_USER && uid!=mail.getMail_reciever_uid()) {
					// 玩家邮件
					return Resp.build(Code.MAIL_NOT_EXIT, "邮件不存在");
				}
				MailRead mailRead = mailReadMapper.findMailReadByUidAndMailId(uid, mail_id);
				if (mailRead != null) {
					return Resp.build(Code.MAIL_READED, "邮件已经阅读过");
				}
				MailReward mailReward = mailRewardMapper.findMailRewardByUidAndMailId(uid, mail_id);
				if (mailReward != null) {
					return Resp.build(Code.MAIL_ALREADY_REWARD, "邮件附件已领取");
				}
				mailRead = new MailRead();
				mailRead.setUid(uid);
				mailRead.setMail_id(mail_id);
				mailRead.setDay_str(day_str);
				mailRead.setCreate_stamp(now);
				mailReadMapper.insert(mailRead);
				boolean addDiamond=false;
				if(mail.getMail_add_dimond()!=null&&mail.getMail_add_dimond()>0) {
					//增加砖石
					addDiamond=true;
				}
				boolean addClubTea=false;
				if(mail.getMail_club_id()!=null&&mail.getMail_club_tea()!=null&&mail.getMail_club_tea()>0) {
					//增加俱乐部茶叶
					addClubTea=true;
				}
				if(addDiamond||addClubTea) {
					//理论上这里需要使用到分布式事务
					mailReward=new MailReward();
					mailReward.setUid(uid);
					mailReward.setMail_id(mail_id);
					mailReward.setDay_str(day_str);
					mailReward.setCreate_stamp(now);
					mailRewardMapper.insert(mailReward);
					if(addDiamond) {
						//增加砖石
						Resp resp=remoteUser.addUserDiamond(uid,mail.getMail_add_dimond(),DiamondChangeType.MAIL_ADD,"邮件增加砖石");
						if(!Code.OK.equals(resp.getCode())) {
							throw new RuntimeException("邮件增加砖石附件失败");
						}
					}
					if(addClubTea) {
						//增加俱乐部茶叶,凭空系统增加茶叶
						Resp resp=tradeService.mailAddPersonGold(mail.getMail_club_id(),uid,mail.getMail_club_tea());
						if(!Code.OK.equals(resp.getCode())) {
							throw new RuntimeException("邮件增加俱乐部茶叶附件失败");
						}
					}
				}
				redisUtil.del(RedisConsts.HOT_MAILLIST_BY_PAGE+"_"+uid);
				redisUtil.del(RedisConsts.HOT_MAILNOTREAD_COUNT+"_"+uid);
				return Resp.build(Code.OK, "阅读成功");
			}
		}, "MAIL"+"_"+uid, 30);
	}

	public Resp mailDel(SimpleUser simpleUser, Integer mail_id) {
		int uid = simpleUser.getUid();
		return lockUtil.lockMethod(new LockMethod<Resp>() {

			@Override
			public Resp lockRun() {
				Date now=new Date();
				String day_str=DatetimeUtil.parseDateToString("yyyy-MM-dd", now);
				Mail mail = mailMapper.getMail(mail_id);
				if (mail == null) {
					return Resp.build(Code.MAIL_NOT_EXIT, "邮件不存在");
				}
				if (mail.getMail_type() == MailType.MAIL_USER && uid!=mail.getMail_reciever_uid()) {
					// 玩家邮件
					return Resp.build(Code.MAIL_NOT_EXIT, "邮件不存在");
				}
				if ((mail.getMail_add_dimond()!=null&&mail.getMail_add_dimond()>0)||(mail.getMail_club_id()!=null&&mail.getMail_club_tea()!=null&&mail.getMail_club_tea()>0)) {
					MailReward mailReward = mailRewardMapper.findMailRewardByUidAndMailId(uid, mail_id);
					if (mailReward == null) {
						return Resp.build(Code.MAIL_NOT_REWARD, "邮件附件未领取");
					}
				}
				MailDel mailDel = mailDelMapper.findMailDelByUidAndMailId(uid, mail_id);
				if(mailDel!=null) {
					return Resp.build(Code.MAIL_READED, "邮件已经删除");
				}
				mailDel = new MailDel();
				mailDel.setUid(uid);
				mailDel.setMail_id(mail_id);
				mailDel.setDay_str(day_str);
				mailDel.setCreate_stamp(now);
				mailDelMapper.insert(mailDel);
				redisUtil.del(RedisConsts.HOT_MAILLIST_BY_PAGE+"_"+uid);
				redisUtil.del(RedisConsts.HOT_MAILNOTREAD_COUNT+"_"+uid);
				return Resp.build(ResponseCode.OK, "删除邮件成功");
			}
		}, "MAIL"+"_"+uid, 30);
	}

	public int findNotReadMailCount(int uid) {
		int count=0;
		String not_read_count=(String) redisUtil.get(RedisConsts.HOT_MAILNOTREAD_COUNT+"_"+uid);
		if(StringUtils.isBlank(not_read_count)) {
			count=mailMapper.mailNotReadCount(uid);
			redisUtil.set(RedisConsts.HOT_MAILNOTREAD_COUNT+"_"+uid,String.valueOf(count),10*60);
		}else {
			count=Integer.valueOf(not_read_count);
		}
		return count;
	}
}
